#!/bin/bash

# 封装ssh命令对服务器进行远程操作
# 传文件
    # scp -i /works/deploy/tang.pem -o StrictHostKeyChecking=no /home/kyo/file.txt root@113.15.23.4:/works/

    # ./kssh push tang-db /home/kyo/file.txt

# 下载文件
    # scp -i /works/deploy/tang.pem -o StrictHostKeyChecking=no root@113.15.23.4:/works/mysql.cnf /home/kyo/mysql.cnf

    # ./kssh pull tang-db /works/mysql.cnf [/home/kyo/mysql.cnf]

# 证书登录
    # ssh -i /works/deploy/tang.pem -o StrictHostKeyChecking=no root@113.15.23.4

    # ./kssh tang-db

# 执行命令
    # ssh -i /works/deploy/tang.pem -o StrictHostKeyChecking=no root@113.15.23.4 'ifconfig'

    # ./kssh tang-db 'ifconfig'

# 服务器列表
declare -A SRVLIST
SRVLIST[tang-py]=root@120.78.72.25
SRVLIST[tang-ad]=root@120.79.60.40

SRVLIST[hf-ad]=root@120.25.216.244

# 错误码对应错误信息
declare -A errMsg
errMsg[1]="The argument cannot be empty"
errMsg[2]="ssh key file parse error"
errMsg[3]="Not\033[31m $1 \033[0mCloud Service"

# ssh scp命令封装变量
test -z "$SSH" && SSH="ssh -o StrictHostKeyChecking=no"
test -z "$SCP" && SCP="scp -o StrictHostKeyChecking=no"

DEBUG=1
KEYDIR=${KEYDIR-/works/deploy}

#------------------------------------------------------------------------------

# SSH非交互式登录执行命令函数
expect_login() {
    local script_file=/tmp/srv_expect
    local host="$1"
    local password="$2"
    local cmd="$3"

    cat > $script_file << EOF
#!/usr/bin/expect -f
set timeout -1
spawn $SSH $host
expect {
"*password:" {send "$password\r"}
"*Permission*" {exit 99\r}
}

expect "#*"
send "$cmd\r"
send "exit 0\r"
expect eof
EOF
    chmod +x $script_file
    $script_file
}

debug() {
    test -z "$DEBUG" || echo -e "$@"
}

err_exit() {
    debug "$@"
    exit ${2-0}
}

cossh() {
    test -z "$1" && return 1

    keyname=${1%-*}
    test -z "$keyname" && return 2

    HOST=${SRVLIST[$1]}
    test -z "$HOST" && return 3

    SSHKEY="$SSH -t -i $KEYDIR/$keyname.pem"
    SCPKEY="$SCP -i $KEYDIR/$keyname.pem"

    shift

    cmd="${1}"
    shift

    case "$cmd" in
        push)
            test -z "$1" && err_exit 'Not File...'
            local filelist="$@"
            local srclist=${filelist% *}
            local dstpath=${filelist##* }
            test -z "$2" && dstpath=/tmp
            debug "$SCPKEY $srclist $HOST:$dstpath"
            $SCPKEY $srclist $HOST:$dstpath
            ;;
        pull)
            debug "$SCPKEY $HOST:$1 ${2-.}"
            $SCPKEY $HOST:$1 ${2-.}
            ;;
        *)
            debug "$SSHKEY $HOST $cmd $@"
            test -z "$cmd" && $SSHKEY $HOST || $SSHKEY $HOST "$cmd $@"
            ;;
    esac
}

